#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <pthread.h>
#include <sys/types.h>
#include <memory>
#include "InetAddr.hpp"
#include "log.hpp"

namespace socket_ns
{
    class Socket;
    class Tcpsocket;
    static const int defaultfd = -1;
    static const int gbacklog = 16;
    using socket_Tsptr = std::shared_ptr<Tcpsocket>;
    using socket_sptr = std::shared_ptr<Socket>;

    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR,
        USAGE_ERROR
    };

    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void BindSocketOrDie(InetAddr &addr) = 0;
        virtual void ListenSocketOrDie() = 0;
      //virtual socket_sptr Accepter(InetAddr *addr) = 0;
        virtual int Accepter(InetAddr *addr) = 0;
        
        virtual bool Connetcor(InetAddr &addr) = 0;
        virtual int SockFd() = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &in) = 0;
        virtual void Close() = 0;
        // virtual void Recv() = 0;
        // virtual void Send() = 0;
        // virtual void other() = 0;

    public:
        void BuildListenSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            BindSocketOrDie(addr);
            ListenSocketOrDie();
        }
        bool BuildClientSocket(InetAddr &addr)
        {
            CreateSocketOrDie();

            std::cout<<"2"<<std::endl;
            return Connetcor(addr);
        }
        // void BuildUdpSocket()
        // {
        //     CreateSocketOrDie();
        //     BindSocketOrDie();
        // }
    };

    class Tcpsocket : public Socket
    {
    public:
        Tcpsocket(int fd = defaultfd) : _sockfd(fd)
        {
        }
        void CreateSocketOrDie() override
        {
            // 1. 创建流式套接字
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket error");
                exit(SOCKET_ERROR);
            }
            LOG(DEBUG, "socket create success, sockfd is : %d\n", _sockfd);
        }
        void BindSocketOrDie(InetAddr &addr) override
        {
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = inet_addr(addr.Ip().c_str());
            local.sin_port = htons(addr.Port());
            int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "bind error");
                exit(BIND_ERROR);
            }
            LOG(DEBUG, "bind success, sockfd is : %d\n", _sockfd);
        }
        void ListenSocketOrDie() override
        {
            int n = ::listen(_sockfd, gbacklog);
            if (n < 0)
            {
                LOG(FATAL, "listen error");
                exit(LISTEN_ERROR);
            }
            LOG(DEBUG, "listen success, sockfd is : %d\n", _sockfd);
        }
        int  Accepter(InetAddr *addr) override
        {
            struct sockaddr_in peer;
            socklen_t socklen = sizeof(peer);
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &socklen); // 客户端信息 返回socket文件描述符
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                return SOCKET_ERROR;
            }
            *addr = peer;
            //socket_sptr sock = std::make_shared<Tcpsocket>(sockfd);
            return sockfd; // 返回新的socket对象 通过这个socket进行io通信
        }
        bool Connetcor(InetAddr &addr) override
        {
            struct sockaddr_in server;
            // 构建目标主机的socket信息
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(addr.Port());
            server.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server)); // 连接目标主机
            if (n < 0)
            {
                std::cerr << "connect error" << std::endl;
                return false;
            }
            return true;
        }
        int Recv(std::string *out) override
        {
            char inbuffer[1024];
            ssize_t n = ::recv(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                *out += inbuffer; // ??? +=
            }
            return n;
        }
        int Send(const std::string &in) override
        {
            int n = ::send(_sockfd, in.c_str(), in.size(), 0);
            return n;
        }
        int SockFd() override
        {
            return _sockfd;
        }
        void Close() override
        {
            if (_sockfd > -1)
                ::close(_sockfd);
        }

    private:
        int _sockfd;
    };
    ///////////////////////////////////
    ///////////////////////////////////
    class Udpsocket : public Socket
    {
        Udpsocket(int fd = defaultfd)
            : _sockfd(fd)
        {
        }
        void CreateSocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "sock error, %s, %d\n", strerror(errno), errno);
                exit(SOCKET_ERROR);
            }
            // 创建成功
            LOG(INFO, "sock create succuss,sockfd:%d", _sockfd);
        }
        void BindSocketOrDie(InetAddr &addr) override
        {
            struct sockaddr_in local; // struct sockaddr_in 系统提供的数据类型。local是变量，用户栈上开辟空间。int a = 100; a = 20;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(addr.Port()); // port要经过网络传输给对面，先到网络，_port：主机序列-> 主机序列，转成网络序列
            local.sin_addr.s_addr = INADDR_ANY;  // htonl(INADDR_ANY);

            int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "bind error, %s, %d\n", strerror(errno), errno);
                exit(BIND_ERROR);
            }
            LOG(INFO, "socket bind success\n");
        }
        int SockFd() override
        {
            return _sockfd;
        }

    private:
        int _sockfd;
    };
};